package com.taiji.dicom4platform.common.log.aspect;
import com.taiji.dicom4platform.common.core.exception.ServiceException;
import com.taiji.dicom4platform.common.core.utils.R;
import com.taiji.dicom4platform.common.core.utils.SpringContextHolder;
import com.taiji.dicom4platform.common.log.event.SysLogEvent;
import com.taiji.dicom4platform.common.log.util.SysLogUtils;
import com.taiji.dicom4platform.common.model.entity.SysLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.time.LocalDateTime;

/**
 * @Description
 * @Author fanxl
 * @Date 2021/5/18
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

	private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public R ServiceException(Exception e) {
		logger.info(getException(e));

		if(e instanceof ServiceException){
			return  R.failed( e.getMessage());
		}
		SysLog logVo = SysLogUtils.getSysLog();
		logVo.setTitle("异常信息捕获");
		logVo.setCreateTime(LocalDateTime.now());
		logVo.setUpdateTime(LocalDateTime.now());
		logVo.setException(getException(e));
		SpringContextHolder.publishEvent(new SysLogEvent(logVo));
		return  R.failed( e.getMessage());
	}

	/**
	 * 将异常日志转换为字符串
	 *
	 * @param e
	 * @return
	 */
	public String getException(Exception e) {
		Writer writer = null;
		PrintWriter printWriter = null;
		try {
			writer = new StringWriter();
			printWriter = new PrintWriter(writer);
			e.printStackTrace(printWriter);
			return writer.toString();
		} finally {
			try {
				if (writer != null) {
					writer.close();
				}
				if (printWriter != null) {
					printWriter.close();
				}
			} catch (IOException e1) {
			}
		}
	}
}
